from flask import Blueprint, request, jsonify
from sqlalchemy.exc import IntegrityError
from api.services import create_user, authenticate_user, create_access_token
from api.database import SessionLocal
from api.models import User, UserData  # 确保正确导入 User 和 UserData 模型
from datetime import datetime, timezone
from utils.response import success, error
from sqlalchemy import text

# 创建蓝图
user_data_bp = Blueprint("user_data", __name__)


# 获取数据库会话
from contextlib import contextmanager


def get_db():
    if SessionLocal is None:
        raise RuntimeError("数据库连接未初始化，请检查配置和连接状态")
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


@contextmanager
def get_db_session():
    """获取数据库会话的上下文管理器"""
    db = None
    try:
        db = next(get_db())
        yield db
    except Exception as e:
        if db:
            db.rollback()
        raise
    finally:
        if db:
            db.close()


@user_data_bp.route("/user-data", methods=["POST"])
def create_user_data():
    """
    创建用户数据接口，支持单条和批量创建
    """
    # 检查请求头是否为 JSON
    if not request.is_json:
        return error(message="请求头 Content-Type 必须为 application/json")

    # 获取 JSON 数据
    data = request.json

    # 检查是否为新的批量创建格式 {"list": [...]}
    if isinstance(data, dict) and "list" in data and isinstance(data["list"], list):
        return create_user_data_batch(data["list"])

    # 检查是否为旧的批量创建格式 [...]
    if isinstance(data, list):
        return create_user_data_batch(data)

    # 单条创建逻辑
    user_id = data.get("user_id")
    date = data.get("date")
    title = data.get("title")
    content = data.get("content", "")

    if not user_id or not date or not title:
        return error(message="用户ID、日期和标题都是必填项")

    with get_db_session() as db:
        # 检查用户是否存在
        user = db.execute(
            text("SELECT * FROM users WHERE id = :user_id"), {"user_id": user_id}
        ).fetchone()

        if not user:
            return error(message="用户不存在")

        # 创建用户数据，处理时区问题
        date_obj = datetime.fromisoformat(date)
        # 如果没有时区信息，假设为UTC时间
        if date_obj.tzinfo is None:
            date_obj = date_obj.replace(tzinfo=timezone.utc)
        # 转换为本地时区时间
        local_date = date_obj.astimezone()

        user_data = UserData(
            user_id=user_id,
            date=local_date,
            title=title,
            content=content,
        )
        db.add(user_data)
        db.commit()
        db.refresh(user_data)

        return success(
            data={
                "id": user_data.id,
                "user_id": user_data.user_id,
                "date": user_data.date.isoformat(),
                "title": user_data.title,
                "content": user_data.content,
                "created_at": user_data.created_at.isoformat(),
                "updated_at": user_data.updated_at.isoformat(),
            },
            message="数据创建成功",
        )


def create_user_data_batch(data_list):
    """
    批量创建用户数据
    """
    if not data_list:
        return error(message="数据列表不能为空")

    with get_db_session() as db:
        created_data = []

        for data in data_list:
            user_id = data.get("user_id")
            date = data.get("date")
            title = data.get("title")
            content = data.get("content", "")

            if not user_id or not date or not title:
                return error(message="用户ID、日期和标题都是必填项")

            # 检查用户是否存在
            user = db.execute(
                text("SELECT * FROM users WHERE id = :user_id"), {"user_id": user_id}
            ).fetchone()

            if not user:
                return error(message=f"用户ID {user_id} 不存在")

            # 创建用户数据，处理时区问题
            date_obj = datetime.fromisoformat(date)
            # 如果没有时区信息，假设为UTC时间
            if date_obj.tzinfo is None:
                date_obj = date_obj.replace(tzinfo=timezone.utc)
            # 转换为本地时区时间
            local_date = date_obj.astimezone()

            user_data = UserData(
                user_id=user_id,
                date=local_date,
                title=title,
                content=content,
            )
            db.add(user_data)
            db.flush()  # 获取ID但不提交
            db.refresh(user_data)

            created_data.append(
                {
                    "id": user_data.id,
                    "user_id": user_data.user_id,
                    "date": user_data.date.isoformat(),
                    "title": user_data.title,
                    "content": user_data.content,
                    "created_at": user_data.created_at.isoformat(),
                    "updated_at": user_data.updated_at.isoformat(),
                }
            )

        db.commit()
        return success(
            data=created_data, message=f"成功创建 {len(created_data)} 条数据"
        )


@user_data_bp.route("/mytool/user-data/<int:data_id>", methods=["GET"])
def get_user_data(data_id):
    """
    获取单条用户数据接口
    """
    with get_db_session() as db:
        user_data = db.execute(
            text("SELECT * FROM user_data WHERE id = :data_id"), {"data_id": data_id}
        ).fetchone()

        if not user_data:
            return error(message="数据不存在")

        return success(
            data={
                "id": user_data.id,
                "user_id": user_data.user_id,
                "date": user_data.date.isoformat(),
                "title": user_data.title,
                "content": user_data.content,
                "created_at": user_data.created_at.isoformat(),
                "updated_at": user_data.updated_at.isoformat(),
            },
            message="数据获取成功",
        )


from api.decorators import token_required


@user_data_bp.route("/mytool/user-data/user/all", methods=["GET"])
@token_required
def get_user_all_data(user):
    """
    获取用户所有数据接口
    """
    with get_db_session() as db:
        # 查询该用户下的所有数据
        user_data_list = db.execute(
            text("SELECT * FROM user_data WHERE user_id = :user_id ORDER BY date DESC"),
            {"user_id": user.id},
        ).fetchall()

        # 组装返回数据
        data = []
        for user_data in user_data_list:
            data.append(
                {
                    "id": user_data.id,
                    "user_id": user_data.user_id,
                    "date": user_data.date.isoformat(),
                    "title": user_data.title,
                    "content": user_data.content,
                    "created_at": user_data.created_at.isoformat(),
                    "updated_at": user_data.updated_at.isoformat(),
                }
            )

        return success(
            data=data, message=f"成功获取用户 {user.id} 的 {len(data)} 条数据"
        )


@user_data_bp.route("/mytool/user-data/<int:data_id>", methods=["PUT"])
def update_user_data(data_id):
    """
    更新用户数据接口
    """
    # 检查请求头是否为 JSON
    if not request.is_json:
        return error(message="请求头 Content-Type 必须为 application/json")

    # 获取 JSON 数据
    data = request.json
    date = data.get("date")
    title = data.get("title")
    content = data.get("content", "")

    with get_db_session() as db:
        # 查找要更新的数据
        user_data = db.execute(
            text("SELECT * FROM user_data WHERE id = :data_id"), {"data_id": data_id}
        ).fetchone()

        if not user_data:
            return error(message="数据不存在")

        # 更新数据
        if date:
            date_obj = datetime.fromisoformat(date)
            # 如果没有时区信息，假设为UTC时间
            if date_obj.tzinfo is None:
                date_obj = date_obj.replace(tzinfo=timezone.utc)
            # 转换为本地时区时间
            user_data.date = date_obj.astimezone()
        if title:
            user_data.title = title
        if content is not None:  # 允许更新为空字符串
            user_data.content = content

        user_data.updated_at = datetime.now(timezone.utc)
        db.commit()

        return success(
            data={
                "id": user_data.id,
                "user_id": user_data.user_id,
                "date": user_data.date.isoformat(),
                "title": user_data.title,
                "content": user_data.content,
                "created_at": user_data.created_at.isoformat(),
                "updated_at": user_data.updated_at.isoformat(),
            },
            message="数据更新成功",
        )


@user_data_bp.route("/mytool/user-data/<int:data_id>", methods=["DELETE"])
def delete_user_data(data_id):
    """
    删除用户数据接口
    """
    with get_db_session() as db:
        # 查找要删除的数据
        user_data = db.execute(
            text("SELECT * FROM user_data WHERE id = :data_id"), {"data_id": data_id}
        ).fetchone()

        if not user_data:
            return error(message="数据不存在")

        # 删除数据
        db.execute(
            text("DELETE FROM user_data WHERE id = :data_id"), {"data_id": data_id}
        )
        db.commit()

        return success(message="数据删除成功")
